<?php
include '../php/config.php';
include 'utils.php';

session_start();

$location = "Location: " . $ISSUER_HOST . "/create_badge_result.php";

$mysqli = new mysqli($MYSQL_HOST, $MYSQL_USERNAME, $MYSQL_PASSWORD, $MYSQL_DB_NAME);
if ($mysqli->connect_errno) {
	$_SESSION[$CB_MSG_TAG] = $DB_CONN_ERR;
	$_SESSION[$DB_CONN_ERRNO] = $mysqli->connect_errno;
	$_SESSION[$DB_CONN_ERROR] = $mysqli->connect_error;
	header($location);
	exit();
}

if ( $_FILES["immagine"]["error"] > 0) {
	$mysqli->close();
	$_SESSION[$CB_MSG_TAG] = $UPLOAD_ERR;
	$_SESSION[$UPLOAD_ERROR] =  $_FILES["immagine"]["error"];
	header($location);
	exit();
}

$_SESSION["nomeBadge"] = trim($_POST["nome"]);
$_SESSION["descrizioneBadge"] = $_POST["descrizione"];
$_SESSION["tagsBadge"] = $_POST["tags"];
$_SESSION["condivisaBadge"] = $_POST["condivisa"];
$_SESSION["categoriaBadge"] = $_POST["categoria"];
$_SESSION["criteria"] = $_POST["criteria"];

$name = trim($_POST['nome']);

$allowedExts = array("png");
$extension = strtolower(end(explode(".", $_FILES["immagine"]["name"])));

if ((($_FILES["immagine"]["type"] == "image/x-png")
		|| ($_FILES["immagine"]["type"] == "image/png"))
		&& in_array($extension, $allowedExts)) {

	$created = move_uploaded_file($_FILES["immagine"]["tmp_name"],
			$BADGE_IMG_PATH_FROM_PHP . "/" . $name . ".png");

	if (!$created) {
		unlink($BADGE_IMG_PATH_FROM_PHP . "/" . $name . ".png");
		$mysqli->close();
		$_SESSION[$CB_MSG_TAG] = $IMG_FILE_ERR;
		header($location);
		exit();
	}

} else {
	$mysqli->close();
	$_SESSION[$CB_MSG_TAG] = $WRONG_IMG_FORMAT;
	header($location);
	exit();
}

$location_criteria= "Location: " . $ISSUER_HOST . "/insert_criteria_page.php";
$location_badge = "Location: " . $ISSUER_HOST . "/php/scripts/insert_badge.php";

if (isset($_POST['criteria']))
	header($location_criteria);
else
	header($location_badge);
?>
